<?php
import("com.yado.DriverNotFoundException");
class DriverManager {
	/**
	 * Enter description here...
	 *
	 * @param string $uri
	 * @return IConnection
	 */
	
	private static $_registeredDrivers = array();
	public static function registerDriver($driverName,$driverClass){
		 self::$_registeredDrivers[$driverName]=$driverClass;
	}
	
	private static $connections = array();
	
	/**
	 * Enter description here...
	 *
	 * @param string $uri
	 * @return IConnection
	 */
	public static function getConnection($uri){
		if (isset(self::$connections[$uri])) return self::$connections[$uri]; 
		$url = parse_url($uri);
		$driver = $url['scheme'];
		$host = $url['host'];
		$db = str_replace("/","",$url['path']);
		$userName = $url['user'];
		$password = $url['pass'];
		if(!isset(self::$_registeredDrivers[$driver])){
			throw new DriverNotFoundException($driver);
		}
		$driverClassUri = self::$_registeredDrivers[$driver];
		$exp = explode(".",$driverClassUri);
		$driverClass = $exp[sizeof($exp)-1];
		try{
			import($driverClassUri);
			$connection = new $driverClass();
		}catch (ClassNotFoundException $e){
			throw new DriverNotFoundException($driver);
		}
		if ($connection instanceof IConnection ){
			$connection->connect($host,$userName,$password,$db);
		}
		return $connection;
		
	}
}

?>